<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="mobile-web-app-capable" content="yes">
  <meta name="HandheldFriendly" content="true"/>

  <title>Styling iink</title>

  <link rel="stylesheet" href="../examples.css">
  <style>
    #editor {
      height: calc(100vh - 80px);
      width: 100%;
    }

    .hidden {
      display: none;
    }

    .style-flex-container {
      display: flex;
      flex-wrap: wrap;
      justify-content: baseline;
    }

    .style-flex-item {
      margin: 12px 12px 0;
    }

    .color-field, .color-field:focus {
      padding: 0;
      height: 36px;
    }

    .width-field {
      height: 36px;
    }

    .label-color {
      vertical-align: super;
    }

    #prompter-css {
      height: 110px;
      width: 70%;
      margin-left: 36px;
      padding: 24px;
      position: absolute;
      bottom: 60px;
      z-index: 30;
      border-radius: 6px;
      background: rgba(240, 240, 240, 0.9);
    }

    #prompter-css-category {
      margin-bottom: 12px;
    }

    @media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
      #editor {
        height: calc(100vh - 200px);
      }

      #prompter-css {
        position: fixed;
        bottom: 12px;
      }

      .style-flex-container {
        flex-direction: column;
        align-items: baseline;
      }
    }

    @media only screen and (max-device-width: 710px) {
      .style-flex-item.theme {
        margin-left: 12px;
      }
    }

    /* Styling */

    .ms-editor {
      background: url(https://farm6.staticflickr.com/5526/10976824044_aebaebdb12_z_d.jpg) no-repeat center center / cover;
      color: #F5F6F7;
    }

    .ms-editor .loader {
      border: none;
      border-radius: 0;
      -webkit-animation: rotate-plan 2.4s infinite ease-in-out;
      animation: rotate-plan 2.4s infinite ease-in-out;
    }

    .ms-editor .error-msg::before {
      content: url();
    }

  </style>

  <script src="https://code.jquery.com/pep/0.4.3/pep.js"></script>
  <script type="text/javascript" src="../../dist/iink.min.js"></script>
</head>

<body>
<nav class="style-flex-container">
  <div class="style-flex-item">
    <input id="penStyleClasses" type="checkbox">
    <label for="penStyleClasses">Apply pen style class (greenThickPen)</label>
  </div>
  <div class="style-flex-item">
    <input id="penenabled" type="checkbox">
    <label for="penenabled">Enable pen color/thickness</label>
  </div>
  <div class="style-flex-item pensettings hidden">
    <label class="label-color" for="pencolor">Color:</label>
    <input id="pencolor" class="input-field color-field" type="color" value="#ff7314">
  </div>
  <div class="style-flex-item pensettings hidden">
    <label for="penwidth">Thickness:</label>
    <input id="penwidth" class="input-field width-field" type="number" min="1" max="5" value="2">
  </div>
  </div>
  <div class="style-flex-item theme">
    <label for="theme">Theme:</label>
    <select id="theme" disabled></select>
  </div>
  <div class="style-flex-item">
    <label for="language">Language:</label>
    <select id="language"></select>
  </div>
  <div class="style-flex-item">
    <label for="fonts">Font:</label>
    <select id="fonts"></select>
  </div>
</nav>
<div id="editor" touch-action="none"></div>
<div id="prompter-css">
  <div id="prompter-css-text">
    Theme or pen style applied will be written here.
  </div>
</div>
<script>
  function request(url) {
    return new Promise(function (resolve, reject) {
      // TODO replace with fetch
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url);
      xhr.onload = resolve;
      xhr.onerror = reject;
      xhr.send();
    });
  }

  const editorElement = document.getElementById('editor');
  const themeSelector = document.getElementById('theme');
  const penEnabled = document.getElementById('penenabled');
  const penSettings = document.getElementsByClassName('pensettings');
  const penColor = document.getElementById('pencolor');
  const penWidth = document.getElementById('penwidth');
  const penStyleClasses = document.getElementById('penStyleClasses');
  const fontsElement = document.getElementById('fonts');
  const languageElement = document.getElementById('language');
  const prompterText = document.getElementById('prompter-css-text');

  const themes = [
    {
      name: 'Normal white theme',
      id: 'normal-white',
      theme: {
        ink: {
          color: '#FFFFFF',
          '-myscript-pen-width': 2
        },
        '.text': {
          'font-size': 12
        }
      }
    }, {
      name: 'Thin green theme',
      id: 'thin-green',
      theme: {
        ink: {
          color: '#2E7D32',
          '-myscript-pen-width': 1
        },
        '.text': {
          'font-size': 10
        }
      }
    }, {
      name: 'Bold red theme',
      id: 'bold-red',
      theme: {
        ink: {
          color: '#B71C1C',
          '-myscript-pen-width': 3
        },
        '.text': {
          'font-size': 14
        }
      }
    }];

  const defaultTheme = 'normal-white';
  themes.forEach((theme) => {
    const selected = defaultTheme === theme.id;
    themeSelector.options[themeSelector.options.length] = new Option(theme.name, theme.id, selected, selected);
  });
  themeSelector.disabled = false;

  function getTheme(themes, id) {
    return themes.filter((theme) => {
      return theme.id === id;
    })[0].theme;
  }

  function getFont() {
    return fontsElement.value;
  }

  function updatePrompter(category, value, category2, value2) {
    if (category && value) {
      prompterText.innerText = `${category} = ${JSON.stringify(value)}`;
      if (category2 && value2) {
        prompterText.innerText += `\n${category2} = ${JSON.stringify(value2)}`;
      }
    } else if (category) {
      prompterText.innerText = category;
    }
  }

  editorElement.addEventListener('loaded', async (evt) => {
    const currentLanguage = evt.target.editor.configuration.recognitionParams.iink.lang;
    const res = await iink.getAvailableLanguageList(evt.target.editor.configuration);

    if (languageElement.options.length === 0) {
      Object.keys(res.result).forEach((key) => {
        const selected = currentLanguage === key;
        languageElement.options[languageElement.options.length] = new Option(res.result[key], key, selected, selected);
      });
    }

    fontsElement.options.length = 0;
    request('https://webdemoapi.myscript.com/api/v4.0/iink/font/google/language/' + currentLanguage)
      .then((e) => {
        const result = JSON.parse(e.target.responseText).result.sort();
        Object.keys(result).forEach((index) => {
          fontsElement.options[fontsElement.options.length] = new Option(result[index], result[index]);
        });
      }, (e) => {
        console.log('Error on get language', e);
      });
  });

  languageElement.addEventListener('change', (e) => {
    editor.penStyle = undefined;
    penEnabled.checked = false;
    penStyleClasses.checked = false;
    updatePrompter('Theme reset');

    const configuration = editorElement.editor.configuration;
    //The path to the language depend of the version of API you are using.
    configuration.recognitionParams.iink.lang = e.target.value;
  });

  fontsElement.addEventListener('change', (e) => {
    const fontFamily = e.target.value;
    const currentTheme = Object.assign({}, getTheme(themes, themeSelector.value));
    currentTheme['.text']['font-family'] = fontFamily;
    editor.theme = currentTheme;
    updatePrompter('editor.theme', currentTheme);
  });

  function getStyle() {
    return {
      color: penColor.value,
      '-myscript-pen-width': penWidth.value
    };
  }

  penStyleClasses.addEventListener('change', (event) => {
    if (event.target.checked) {
      const classesTheme = Object.assign({}, getTheme(themes, themeSelector.value));
      classesTheme['.greenThickPen'] = {
        color: '#00FF00',
        '-myscript-pen-width': 3
      };

      editor.theme = classesTheme;
      editor.penStyleClasses = 'greenThickPen';
      updatePrompter('editor.theme', classesTheme, 'editor.penStyleClasses', 'greenThickPen');

    } else {
      editor.penStyle = undefined;
      editor.theme = getTheme(themes, themeSelector.value);
      updatePrompter('editor.theme', getTheme(themes, themeSelector.value));
    }
  });

  themeSelector.addEventListener('change', (event) => {
    const selectedTheme = getTheme(themes, event.target.value);
    selectedTheme['.text']['font-family'] = getFont();
    if (selectedTheme) {
      editor.theme = selectedTheme;
      updatePrompter('editor.theme', selectedTheme);
    }
  });
  penEnabled.addEventListener('change', (event) => {
    if (event.target.checked) {
      penSettings[0].classList.remove('hidden');
      penSettings[1].classList.remove('hidden');
      editor.penStyle = getStyle();
      updatePrompter('editor.penStyle', getStyle());
    } else {
      penSettings[0].classList.add('hidden');
      penSettings[1].classList.add('hidden');
      editor.penStyle = undefined;
      updatePrompter('editor.penStyle', "");
    }
  });
  penColor.addEventListener('change', () => {
    editor.penStyle = getStyle();
    updatePrompter('editor.penStyle', getStyle());
  });
  penWidth.addEventListener('change', () => {
    editor.penStyle = getStyle();
    updatePrompter('editor.penStyle', getStyle());
  });


  /**
   * Attach an editor to the document
   * @param {Element} The DOM element to attach the ink paper
   * @param {Object} The recognition parameters
   */
  const editor = iink.register(editorElement, {
      recognitionParams: {
        type: 'TEXT',
        protocol: 'WEBSOCKET',
        server: {
          scheme: 'https',
          host: 'webdemoapi.myscript.com',
          applicationKey: '515131ab-35fa-411c-bb4d-3917e00faf60',
          hmacKey: '54b2ca8a-6752-469d-87dd-553bb450e9ad'
        }
      }
    },
    undefined, getTheme(themes, defaultTheme));

  window.addEventListener('resize', () => {
    editorElement.editor.resize();
  });
</script>
</body>

</html>